import 'package:flutter/material.dart';
import '../../manger/network_utils.dart';
import '../../l10n/app_localizations.dart';
import '../view/login_thridlogin_view.dart';
import '../view/custom_text_field.dart';
import '../view/protocol_view.dart';
import '../../components/toast_utils.dart';
import '../view/mobile_text_field.dart';
import '../view/custom_text_field2.dart';

import '../view/protocol_dialog.dart';
import '../controller/regis_view.dart';
import '../../components/custom_dialog.dart';
import '../../models/user_info_model.dart';
import '../../manger/user_manger.dart';
import '../../components/click_word_captcha.dart';
import '../../manger/qysdk_manger.dart';
import '../../manger/umevent_utils.dart';

class LoginCenterView extends StatefulWidget {
  final VoidCallback? onLoginSuccess;
  const LoginCenterView({super.key, this.onLoginSuccess});

  @override
  State<LoginCenterView> createState() => _LoginCenterViewState();
}

class _LoginCenterViewState extends State<LoginCenterView> {

  void _showLogoutDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => CustomDialog(
        title: AppLocalizations.of(context)!.accountNotRegistered,
        description: AppLocalizations.of(context)!.theaccountyou,
        leftButtonText: AppLocalizations.of(context)!.cancel,
        rightButtonText: AppLocalizations.of(context)!.registerNow,
        onLeftPressed: () => Navigator.pop(context),
        onRightPressed: () {
          Navigator.pop(context);
          pushRegister();
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
  }

  final TextEditingController _usernameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  var loginType = 0;
  var code = 'US +1';
  var captchaVerification = '';

  void login() async {
    var params = {};
    if (loginType == 0) {
      UmengEvent.trackEvent("login_email_log","登录页选择邮箱登录，且点击登录按钮","");
      params = {
        'username': _usernameController.text,
        'password': _passwordController.text,
        'loginState': loginType,
        'captchaVerification': captchaVerification,
      };
    } else {
      UmengEvent.trackEvent("login_phone_log","登录页选择手机号登录，且点击登录按钮","");
      params = {
        'username': _usernameController.text,
        'password': _passwordController.text,
        'loginState': loginType,
        'areaCode': code,
        'captchaVerification': captchaVerification,
      };
    }

    if (mounted) {
      ToastUtils.showLoadingToast(context);
    }

    try {
      final response = await NetworkUtils.post(
        RequestCmd.login,
        body: params,
      );
      captchaVerification = "";
      ToastUtils.dismissLoadingToast();
      if (response.toString().contains('201')) {
        if (mounted) {
          _showLogoutDialog(context);
        }
      } else {
        final model = LoginModel.fromJson(response);
        if (model.code == 200) {
          if (model.data?.model != null) {
            final tokenModel = model.data!.model!;
            UserInfos.shared.saveToken(tokenModel.accessToken);
            loginType == 0 ? UmengEvent.trackEvent("login_email_success","邮箱登录成功","") : UmengEvent.trackEvent("login_phone_success","手机登录成功","");
            widget.onLoginSuccess?.call();
          } else if (model.data?.boolValue != null) {
            // 处理bool情况
            final boolValue = model.data!.boolValue!;
            if(boolValue){
              loadingClickWord(context);
            }
          }
        } else {
          ToastUtils.showCenterToast(context, model.msg ?? '登录失败,请联系客服');
        }
      }
    } catch (e) {
      ToastUtils.dismissLoadingToast();
    }
  }

    //点选拼图
  void loadingClickWord(BuildContext context, {barrierDismissible = true}) {
    showDialog<Null>(
      context: context,
      barrierDismissible: barrierDismissible,
      builder: (BuildContext context) {
        return ClickWordCaptcha(
          onSuccess: (v){
            captchaVerification = v;
            login();
          },
          onFail: (){
            Navigator.pop(context);
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(15),
      child: Container(
        color: Colors.white, // 设置背景色为白色
        child: SizedBox(
          width: MediaQuery.of(context).size.width - 50,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              LoginThirdLoginView(
                type: 1, 
                onThridLoginSuccess: () {
                  widget.onLoginSuccess?.call();
                }
                ),
              Padding(
                padding: EdgeInsets.only(left: 15, top: 10,bottom: 5),
                child: Text(
                  AppLocalizations.of(context)!.yonghudenglu,
                  style: TextStyle(
                    fontSize: 14,
                    fontWeight: FontWeight.bold,
                    color: Color(0xFF222222),
                  ),
                ),
              ),
              AutofillGroup(
                child: Column(
                  children: [
                    Padding(
                padding: EdgeInsets.symmetric(horizontal: 18, vertical: 10),
                child: _usernameController.text.isNotEmpty && !_usernameController.text.contains('@')
                    ? MobileTextField(
                        controller: _usernameController,
                        hintText: '',
                        autofillHints: [AutofillHints.username],
                        onChanged: (value) {
                          
                        },
                        onFocusLost: () {
                          if (_usernameController.text.isNotEmpty && !_usernameController.text.contains('@')) {
                            setState(() {
                              loginType = 3;
                            });
                          } else{
                            setState(() {
                              loginType = 0;
                            });
                          }
                        },
                        onCodeValueChanged: (value) {
                          if (_usernameController.text.isNotEmpty && !_usernameController.text.contains('@')) {
                            setState(() {
                              loginType = 3;
                            });
                          } else{
                            setState(() {
                              loginType = 0;
                            });
                          }
                          setState(() {
                            final parts = value.split(' ');
                            code = parts[1].startsWith('+') ? parts[1].substring(1) : parts[1];
                          });
                        },
                      )
                    : CustomTextField(
                        controller: _usernameController,
                        autofillHints: [AutofillHints.username],
                        hintText: '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.mailbox}/${AppLocalizations.of(context)!.phoneNumber},${AppLocalizations.of(context)!.logindesc}',
                        onEditingComplete: () {
                          if (_usernameController.text.isNotEmpty && !_usernameController.text.contains('@')) {
                            setState(() {
                              loginType = 3;
                            });
                          } else{
                            setState(() {
                              loginType = 0;
                            });
                          }
                        },
                        onFocusLost: () {
                          if (_usernameController.text.isNotEmpty && !_usernameController.text.contains('@')) {
                            setState(() {
                              loginType = 3;
                            });
                          } else{
                            setState(() {
                              loginType = 0;
                            });
                          }
                        },
                        onChanged: (value) {
                        },
                      ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: CustomTextField(
                  controller: _passwordController,
                  autofillHints: [AutofillHints.password],
                  hintText: AppLocalizations.of(context)!.pleaseEnter + AppLocalizations.of(context)!.login + AppLocalizations.of(context)!.password,
                  obscureText: true,
                ),
              ),
                  ],
                ),
              ),

              ProtocolView(),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF5D5FEE),
                    minimumSize: Size.fromHeight(50),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(22),
                    ),
                  ),
                  onPressed: () {
                    if (_usernameController.text.isEmpty){
                      ToastUtils.showCenterToast(context, '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.mailbox}/${AppLocalizations.of(context)!.phoneNumber}');
                      return;
                    }
                    if (_passwordController.text.isEmpty){
                      ToastUtils.showCenterToast(context, '${AppLocalizations.of(context)!.pleaseEnter}${AppLocalizations.of(context)!.login}${AppLocalizations.of(context)!.password}');
                      return;
                    }
                    if (!ProtocolView.isSelected) {
                      showDialog(
                        context: context,
                        builder: (context) => ProtocolDialog(onCancel: () {
                          Navigator.pop(context);
                        },onSure: () {
                          setState(() {
                            ProtocolView.isSelected = true;
                            login();
                          });
                        },),
                      );
                      return;
                    }
                    login();
                  },
                  child: Text(
                    AppLocalizations.of(context)!.login,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
                child: ElevatedButton(
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.white,
                    minimumSize: Size.fromHeight(50),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(22),
                      side: BorderSide(color: Color(0xFF5D5FEE)),
                    ),
                  ),
                  onPressed: () {
                    pushRegister();
                  },
                  child: Text(
                    AppLocalizations.of(context)!.register,
                    style: TextStyle(
                      color: Color(0xFF5D5FEE),
                      fontSize: 14,
                    ),
                  ),
                ),
              ),
              
              Padding(
                padding: EdgeInsets.only(right: 15),
                child: Align(
                  alignment: Alignment.centerRight,
                  child: GestureDetector(
                    onTap: () {
                      UmengEvent.trackEvent("login_forgetpassword","登录页点击找回密码","");
                      QYSDK.showQYSession();
                    },
                    child: Text(
                      AppLocalizations.of(context)!.forgotPassword,
                      style: TextStyle(
                        fontSize: 13,
                        color: Color(0xFF4187FD),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  void pushRegister(){
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => RegisView(),
      ),
    );
  }
}